import { defineStore } from 'pinia'
import { userInformation } from '@api/userApi'
import wx from 'weixin-js-sdk'
import { useMainStore } from '@/store'
import router from '@/router'
import { isMiniProgram } from '@/utils'

export const useUserStore = defineStore('user-store', {
  state: () => {
    return {
      token: localStorage.getItem('token') || null,
      role: null,
      nickname: null,
      head_img: null,
      expiration_at: null,
      edition: null,
      invite_id: null,
      uid: null,
    }
  },
  getters: {
    isLogin(state) {
      return Boolean(state.token)
    },
  },
  actions: {
    setUserState(info) {
      const { token } = info
      const _token = `Bearer ${token}`
      localStorage.setItem('token', _token)
      this.$patch({
        token: _token,
      })
    },
    async getUserInfo() {
      const that = this
      useMainStore().setPageLoading(true)
      return new Promise((resolve, reject) => {
        userInformation()
          .then(async res => {
            if (res?.statusCode !== 200) return false
            const { role, nickname, head_img, expiration_at, invite_id, uid } = res.data
            const bool = await isMiniProgram()
            if (bool) {
              wx.miniProgram.postMessage({
                data: {
                  type: 'setUserInviteId',
                  data: invite_id,
                },
              })
            }
            that.$patch({ role, nickname, head_img, expiration_at, invite_id, uid })
            if (expiration_at && +new Date(expiration_at) > +new Date()) {
              that.$patch({ edition: 'plus' })
            } else {
              that.$patch({ edition: 'free' })
            }
            resolve(res)
          })
          .catch(err => {
            reject(err)
            that.logout()
          })
          .finally(() => {
            useMainStore().setPageLoading(false)
          })
      })
    },
    logout() {
      localStorage.removeItem('token')
      this.$patch({ token: '' })
      router.replace('/').finally(() => {
        $message.destroyAll()
        location.reload()
      })
    },
  },
})
